<template>
  <div class="external-treatment-container">
    <!-- 外治处方三 -->
    <div class="custom-table external-treatment-prescription">
      <!-- 标题栏 -->
      <div class="table-header" style="justify-content: space-between">
        <div style="display: flex">
          <div
            class="header-cell"
            style="width: 100px; color: #000000; font-weight: 600"
          >
            {{ externalTreatment.rxName || '外治处方' }}
          </div>
          <div class="form-item">
            <el-select
              v-model="externalTreatment.extInfo.projectType"
              style="width: 140px; height: 36px"
              class="borderless-select borderless-select_1"
              :suffix-icon="CaretBottom"
              filterable
              placeholder=""
              @change="faeeStandardList"
              :disabled="visitStatus == '2'"
            >
              <el-option
                v-for="item in EXT_TYPE"
                :key="item.itemCode"
                :label="item.itemName"
                :value="item.itemCode"
              />
            </el-select>
          </div>
        </div>
        <div class="header-cell" v-if="visitStatus == '1'">
          <div
            class="header-cell"
            @click="removeRow_1(externalTreatment.extInfo.detailList)"
          >
            <img src="@/assets/manage/icon_del_nor.svg" alt="" />
          </div>
        </div>
      </div>

      <!-- 处方选择行 -->
      <div class="prescription-form-row">
        <div class="form-item">
          <el-select
            v-model="externalTreatment.extInfo.projectId"
            filterable
            style="width: 140px; height: 36px"
            class="borderless-select borderless-select_1"
            :suffix-icon="CaretBottom"
            placeholder=""
            v-if="visitStatus !== '2'"
          >
            <!-- <el-option label="激光" value="jiguang" />
            <el-option label="成人针灸套餐" value="adult_acupuncture" />
            <el-option label="推拿套餐" value="massage" /> -->
            <el-option
              v-for="item in faeeStandard"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId"
            />
          </el-select>
          <span v-else>{{ externalTreatment.extInfo.projectName }}</span>
        </div>

        <div class="form-item">
          <el-select
            v-model="externalTreatment.extInfo.frequencyCode"
            style="width: 120px"
            filterable
            class="borderless-select borderless-select_1"
            :suffix-icon="CaretBottom"
            placeholder=""
            v-if="visitStatus !== '2'"
          >
            <el-option
              v-for="frequency in frequency"
              :key="frequency.frequencyCode"
              :label="frequency.frequencyName"
              :value="frequency.frequencyCode"
              style="padding: 0 8px"
            >
              <span style="float: left">{{ frequency.frequencyCode }}</span>
              <span style="float: right; font-size: 13px">
                {{ frequency.frequencyName }}
              </span>
            </el-option>
          </el-select>
          <span v-else>{{ externalTreatment.extInfo.frequencyCodeText }}</span>
        </div>
        <div class="form-item">
          <el-input-number
            v-model="externalTreatment.extInfo.cycle"
            :min="1"
            :max="999"
            :controls="false"
            class="borderless-input"
            style="width: 50px; height: 36px"
            v-if="visitStatus !== '2'"
            @focus="
              showKeyboard(
                externalTreatment.extInfo,
                externalTreatment.extInfo.uuid,
                'cycle'
              )
            "
            @click.stop
          />
          <span v-else>{{ externalTreatment.extInfo.cycle }}</span>
          {{ externalTreatment.extInfo.cycleUnitText }}
          <!-- 数字键盘 -->
          <div
            v-if="
              keyboardVisible &&
              isCurrentEditRow === externalTreatment.extInfo.uuid &&
              currentEditField === 'cycle'
            "
            class="number-keyboard"
            @click.stop
          >
            <NumericKeyboardInt @input="inputNumber" @delete="deleteNumber" />
          </div>
        </div>

        <!-- <div class="form-item" v-if="externalTreatment.extInfo.cycleUnitText">
          <span class="unit-text"></span>
        </div> -->
        <div class="form-item">
          <AutocompleteMulti
            v-model="externalTreatment.extInfo.remark"
            class="borderless-input1"
            placeholder="备注"
            :trigger-on-focus="true"
            :fetch-suggestions="queryRemarkAsync"
            :selected-color="'#16ada4'"
            v-if="visitStatus !== '2'"
          />
          <span v-else class="multi-line">
            {{ externalTreatment.extInfo.remark }}
          </span>
        </div>
      </div>

      <!-- 穴位选择区域 -->
      <div class="acupoint-selection-area">
        <div class="acupoint-row">
          <!-- 左侧组合选择框 -->
          <div
            v-if="externalTreatment.extInfo.detailList.length > 0"
            class="combined-select-group"
            v-for="(item, index) in externalTreatment.extInfo.detailList"
            :key="index"
          >
            <el-select
              v-model="item.sideType"
              filterable
              style="width: 60px"
              class="borderless-select left-select"
              :suffix-icon="CaretBottom"
              placeholder="双"
               :disabled="visitStatus == '2'"
            >
              <el-option
                v-for="frequency in acupointSideTypeEnum"
                :key="frequency.text"
                :label="frequency.text"
                :value="frequency.value"
              />
            </el-select>
            <el-autocomplete
              v-model="item.acupointName"
              style="width: 80px"
              class="borderless-select right-select"
              :suffix-icon="CaretBottom"
              placeholder=""
              :fetch-suggestions="querySearchAsync"
              v-if="visitStatus == '1'"
            >
              <!-- <el-option
                v-for="item in AcupointList"
                :key="item.acupointCode"
                :label="item.acupointText"
                :value="item.acupointCode"
              /> -->
            </el-autocomplete>
              <span v-else style="padding: 0 10px">{{ item.acupointName }}</span>
            <div
              class="delete-icon"
               v-if="visitStatus != '2'"
              @click="externalTreatment.extInfo.detailList.splice(index, 1)"
            >
              <img src="@/assets/icon/icon_off2_hover.svg" alt="" />
            </div>
          </div>
          <div class="acupoint-selector"   v-if="visitStatus != '2'">
            <span class="selector-text">穴位-选中</span>
            <!-- <el-icon class="selector-icon" size="16" @click="onAcupoint">
              <Star />
            </el-icon> -->
            <img
              src="@/assets/icon/icon_xuewei_nor.svg"
              alt=""
              @click="onAcupoint"
              class="selector-icon"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 检验 -->
    <div>
      <el-dialog
        v-model="dialogVisible"
        class="custom-transition-dialog"
        width="50%"
      >
        <acupoint
          :dialogVisible="dialogVisible"
          @close="dialogVisible = false"
          @confirm="handleExamineConfirm"
          ref="examineRef"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, nextTick, onMounted, onUnmounted } from 'vue';
import { CaretBottom, Star, Delete, Close } from '@element-plus/icons-vue';
import AutocompleteMulti from '@/components/AutocompleteMulti.vue';
import stores from '@/store';
import { getAcupointByName, getFeeStandardList } from '@/api/formwork/index';
import { v4 as uuidv4 } from 'uuid';
const useBaseData = stores.useBaseDataStore();
const frequency = ref(useBaseData.getDictsSelect('FREQUENCY'));
const EXT_TYPE = useBaseData.getDictsSelect('EXT_TYPE');
const acupointSideTypeEnum = ref(
  useBaseData.getEnumSelect('acupointSideTypeEnum')
);
const AcupointList = ref<any>([]);
const faeeStandard = ref<any>([]);
const emit = defineEmits(['removeRow']);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<any>(null);
const cycleUnitEnum = ref(useBaseData.getEnumSelect('cycleUnitEnum'));
const dialogVisible = ref(false);
const examineRef = ref<any>(null);
const keyboardVisible = ref(false);
const isCurrentEditRow = ref<any>(null);
const props = defineProps({
  externalTreatment: {
    type: Object,
    default: () => {},
  },
  visitStatus: {
    type: String,
    default: '',
  },
  recomScene: {
    type: String,
    default: '',
  },
});
const faeeStandardList = async () => {
  const data = {
    projectCategory: '3',
    projectType: externalTreatment.value.extInfo.projectType,
  };
  const feeStandardList = await getFeeStandardList(data);
  faeeStandard.value = feeStandardList.data;
};
// 外治处方数据
const externalTreatment = ref<any>({
  medicineType: '小儿针灸套餐',
  dosage: '',
  frequency: '1日1次',
  remark: '',
  leftSide: '双',
  needleType: '速中',
  direction: '左',
  location: '太渊',
});
watch(
  () => props.externalTreatment,
  (newVal) => {
    //console.log('外治处方数据变化:', newVal);

    externalTreatment.value = newVal || {};
    faeeStandardList();
    //console.log(externalTreatment.value);
  },
  { immediate: true }
);
// 工具：是否双侧（常见取值兼容）
const isDoubleSide = (sideType: any) =>
  sideType === '双' ||
  sideType === '2' ||
  sideType === 2 ||
  sideType === 'double' ||
  sideType === 'both';

// 根据收费类型(chargeType)按规则更新数量：
// chargeType === 1 => 数量 = frequencyTimes * cycle
// chargeType === 2 => 数量 = frequencyTimes * cycle * 穴位数（双侧翻倍）
const updateQuantityByChargeType = () => {
  const extInfo = externalTreatment.value?.extInfo as any;
  if (!extInfo) return;
  const matched = faeeStandard.value?.find(
    (i: any) => i.projectId === extInfo.projectId
  );
  if (!matched) return;
  const times = Number(extInfo.frequencyTimes) || 1;
  const cycle = Number(extInfo.cycle) || 1;
  if (String(matched.chargeType) === '1') {
    externalTreatment.value.totalAmount = times * cycle * matched.price; // 按次数
  } else if (String(matched.chargeType) === '2') {
    const list = Array.isArray(extInfo.detailList) ? extInfo.detailList : [];
    const acupointCount = list.reduce(
      (sum: number, it: any) => sum + (isDoubleSide(it?.sideType) ? 2 : 1),
      0
    );
    externalTreatment.value.totalAmount =
      times * cycle * (acupointCount || 0) * matched.price;
  }
};
// 监听 frequencyCode 变化
watch(
  () => externalTreatment.value?.extInfo?.frequencyCode,
  (newVal) => {
    // 赋值给 cycleUnitCode
    if (!newVal) return;
    externalTreatment.value.extInfo.cycleUnitCode = newVal;
    // 匹配 cycleUnitEnum
    const data = frequency.value.find(
      (item: any) => item.frequencyCode === newVal
    );
    const match = cycleUnitEnum.value.find(
      (item: any) => item.value === data.cycleUnit
    );
    externalTreatment.value.extInfo.cycleUnitText = match ? match.text : '';
    externalTreatment.value.extInfo.frequencyTimes = data.frequencyTimes;
    externalTreatment.value.extInfo.uuid = uuidv4();
    // 频次改变后，若收费类型为按次数计费(1)，同步更新数量
    updateQuantityByChargeType();
  }
);
// 监听项目类型变化，按收费类型决定数量规则
watch(
  () => externalTreatment.value?.extInfo?.projectId,
  () => {
    updateQuantityByChargeType();
  }
);
// 监听周期变化，若为按次数计费，同步更新数量
watch(
  () => externalTreatment.value?.extInfo?.cycle,
  () => {
    updateQuantityByChargeType();
  }
);
// 监听穴位列表中每项的 sideType 变化（新增/删除/修改侧别）时重算
watch(
  () => {
    const list = externalTreatment.value?.extInfo?.detailList || [];
    // 读取 sideType 以建立依赖，只有 sideType 改变或条目增删时触发
    return list.map((it: any) => it?.sideType);
  },
  () => {
    updateQuantityByChargeType();
  }
);
// 费用标准加载后尝试重算一次
// watch(
//   () => faeeStandard.value,
//   () => updateQuantityByChargeType()
// );
const handleSelect = (item: any) => {
  //console.log('选中项:', item);
};
// 数字键盘相关方法
const showKeyboard = (row: any, index: number, field: any) => {
  currentEditRow.value = row;
  isCurrentEditRow.value = index;
  currentEditField.value = field;
  keyboardVisible.value = true;
};
const inputNumber = (num: string) => {
  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  // 获取当前值，如果不存在则使用默认值
  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    // 设置默认值
    currentEditRow.value[currentEditField.value] = parseInt(num);
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = parseInt(currentValueStr + num);

  const maxValue = currentEditField.value === 'cycle' ? 365 : 999;
  if (newValue <= maxValue) {
    currentEditRow.value[currentEditField.value] = newValue;
  } else {
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    //console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    //console.log('deleteNumber: current value is undefined/null');
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
};
const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }

  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};
const handleExamineConfirm = (data: any) => {
  //console.log('选中的穴位数据:', externalTreatment.value.extInfo.detailList);
  const list = data.map((item: any) => {
    return {
      acupointCode: item.acupointCode,
      sideType: item.sideType,
      acupointName: item.acupointText,
    };
  });
  externalTreatment.value.extInfo.detailList =
    externalTreatment.value.extInfo.detailList.concat(list);
  dialogVisible.value = false;
};
const onAcupoint = () => {
  dialogVisible.value = true;
  nextTick(() => {
    if (examineRef.value) {
      examineRef.value.onreset();
    }
  });
};
const getAcupointListByText = async (text: string) => {
  try {
    const response = await getAcupointByName({ acupointText: text });
    //console.log(response);

    AcupointList.value = response.data;
  } catch (error) {
    //console.error('Error fetching acupoint list:', error);
    return [];
  }
};
const removeRow_1 = (group: any) => {
  if (group) {
    emit('removeRow', group);
  }
};
const querySearchAsync = (queryString: string, cb: any) => {
  const data = {
    acupointText: queryString,
  };
  getAcupointByName(data).then((res) => {
    const results = res.data.map((item: any) => ({
      value: item.acupointText,
      ...item,
    }));
    cb(results);
  });
};
// 备注建议：仅取 rxType === 4 的项
const queryRemarkAsync = (queryString: string, cb: any) => {
  const data = useBaseData.getDictsSelect('REMARK') || [];
  const filtered = (Array.isArray(data) ? data : []).filter(
    (item: any) => item?.rxType === 4 || item?.rxType === '4'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
onMounted(() => {
  getAcupointListByText('');
  // faeeStandardList();
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
  };
  document.addEventListener('mousedown', globalClickHandler);
});

onUnmounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
  };
  document.removeEventListener('mousedown', globalClickHandler);
});
defineExpose({
  externalTreatment,
});
</script>

<style lang="scss" scoped>
.multi-line {
  display: -webkit-box; /* 使用flexbox布局 */
  -webkit-line-clamp: 2; /* 限制显示行数 */
  -webkit-box-orient: vertical; /* 垂直排列 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
}
::v-deep(.el-input__wrapper) {
  padding-left: 5px !important;
  padding-right: 5px !important;
}
:deep(.borderless-input1) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
    height: 36px;
  }
}
.external-treatment-container {
  background-color: #fff;
  margin-bottom: 10px;
  .custom-table {
    width: 100%;
    border: 1px solid #e7e7e7;
    border-radius: 12px;
    background: #ffffff;

    .table-header {
      display: flex;
      padding: 12px 16px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #e4e7ed;
      align-items: center;

      .header-cell {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #333333;
        cursor: pointer;
        .delete-icon {
          color: #c0c4cc;
          cursor: pointer;

          &:hover {
            color: #f56c6c;
          }
        }
      }
    }

    .prescription-form-row {
      display: flex;
      align-items: center;
      padding: 16px;
      gap: 12px;
      border-bottom: 1px solid #f0f0f0;

      .form-item {
        display: flex;
        align-items: center;
        position: relative;
        .unit-text {
          font-size: 14px;
          color: #333;
          margin-left: 4px;
        }
      }
    }

    .acupoint-selection-area {
      padding: 16px;

      .acupoint-row {
        display: flex;
        align-items: center;
        gap: 12px;
        flex-wrap: wrap;
        .combined-select-group {
          display: flex;
          align-items: center;
          box-shadow: 0 0 0 1px #dcdfe6;
          border-radius: 5px;
          position: relative;

          &:focus-within {
            box-shadow: 0 0 0 1px #409eff !important;
          }

          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc !important;
          }

          .left-select {
            height: 100%;
            :deep(.el-input__wrapper) {
              border: none !important;
              border-radius: 0 !important;
              box-shadow: none !important;
              height: 38px;
            }

            :deep(.el-input__wrapper:focus) {
              box-shadow: none !important;
              border: none !important;
            }

            :deep(.el-input__wrapper:hover) {
              box-shadow: none !important;
              border: none !important;
            }
          }

          .right-select {
            height: 100%;
            :deep(.el-input__wrapper) {
              border: none !important;
              border-radius: 0 !important;
              box-shadow: none !important;
              height: 38px;
            }

            :deep(.el-input__wrapper:focus) {
              box-shadow: none !important;
              border: none !important;
            }

            :deep(.el-input__wrapper:hover) {
              box-shadow: none !important;
              border: none !important;
            }
          }

          .select-divider {
            width: 1px;
            height: 24px;
            background-color: #e4e7ed;
            flex-shrink: 0;
            margin: 0 2px;
          }

          &:hover {
            border-color: #c0c4cc;
          }

          &:focus-within {
            border-color: #409eff;
            /* 只显示右边线的方法 */
            box-shadow: inset -1px 0 0 0 rgba(64, 158, 255, 0.3);
          }
        }

        .acupoint-group {
          display: flex;
          align-items: center;
        }

        .remove-button {
          display: flex;
          align-items: center;
          margin-left: auto;
          margin-right: 12px;

          .remove-btn {
            padding: 4px;
            color: #c0c4cc;

            &:hover {
              color: #f56c6c;
            }
          }
        }

        .acupoint-selector {
          display: flex;
          align-items: center;
          gap: 8px;
          background: #ffffff;
          padding: 8px 12px;
          border-radius: 6px;
          border: 1px solid #e4e7ed;
          cursor: pointer;
          transition: all 0.2s;
          height: 51px;
          &:hover {
            background: #e9ecef;
            border-color: #409eff;
          }

          .selector-text {
            font-size: 14px;
            color: #666;
          }

          .selector-icon {
            color: #f56c6c;
          }
        }
      }
    }
  }

  // 无边框选择框样式
  :deep(.borderless-select) {
    .el-input__wrapper {
      // border: 1px solid #dcdfe6;
      box-shadow: none;
      border-radius: 6px;
      height: 36px !important;
    }

    &:hover .el-input__wrapper {
      border-color: #c0c4cc;
    }

    &.is-focus .el-input__wrapper {
      border-color: #409eff;
    }

    .el-input__suffix {
      .el-input__suffix-inner {
        .el-icon {
          color: #909399;
        }
      }
    }
  }
  .delete-icon {
    position: absolute;
    top: -3px;
    right: 0;
  }
  // 无边框输入框样式
  :deep(.borderless-input) {
    .el-input__wrapper {
      border: 1px solid #dcdfe6;
      box-shadow: none;
      border-radius: 6px;
    }

    &:hover .el-input__wrapper {
      border-color: #c0c4cc;
    }

    &.is-focus .el-input__wrapper {
      border-color: #409eff;
    }
  }
}
// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 9999 !important;
  border-radius: 8px;
  padding: 8px;
  margin-top: 4px;
  transform: translateZ(0); // 硬件加速，确保显示在最顶层

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px; // 退格键宽度是两个按钮+间距
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}
</style>
<style lang="scss">
.left-select {
  .el-select__wrapper {
    height: 51px;
    background-color: rgba(220, 220, 220, 0.1) !important;
    box-shadow: inset -1px 0 0 0 #dcdfe6;
  }
  .el-select__wrapper:hover {
    box-shadow: inset -1px 0 0 0 #dcdfe6 !important;
  }
  .el-select__wrapper:focus-within {
    border-color: #409eff;
    box-shadow: inset -1px 0 0 0 rgba(64, 158, 255, 0.3);
  }
}
.right-select {
  .el-select__wrapper {
    height: 51px;
    box-shadow: none !important;
  }
  .el-select__wrapper:hover {
    box-shadow: none !important;
  }
  .el-select__wrapper:focus-within {
    box-shadow: none !important;
    border: none !important;
  }
}
.borderless-select_1 {
  position: relative;
  .el-select__wrapper {
    height: 36px !important;
  }
}
</style>
